import json
from tabnanny import check

# 导入Django核心模块中的序列化器，用于将Django模型转换为其他格式，如JSON、XML等
from django.core import serializers

# 导入Django序列化功能，以便在需要时将模型序列化
from django.core.serializers import serialize
from django.db.models import Q

# 导入HttpResponse和JsonResponse类，用于构建HTTP响应和JSON响应
from django.http import HttpResponse, JsonResponse

# 导入render函数，它用于根据请求和模板渲染网页
from django.shortcuts import render

from django.views import View
# 导入分页类
from django.core.paginator import Paginator
from backend.models import TCheckitem





class Tab_CheckieView(View):
    def get(self, request, Page):
        Check_Item_list = TCheckitem.objects.filter(is_del=1)
        Check_Item_Json_List = json.loads(serializers.serialize('json', Check_Item_list))
        data_list = []
        for Check_Item_Json in Check_Item_Json_List:
            # if Check_Item_Json["fields"]["is_del"]==1:

            data_josn = Check_Item_Json["fields"]
            CheckItem_id = Check_Item_Json['pk']  # 取检查项id
            data_josn["id"] = CheckItem_id  # 将检查项id赋值给id字段
            # print(CheckItem_id)
            data_list.append(data_josn)
        result = {
            "status": "200",
            "message": "获取检查项成功",

            "data": data_list

        }
        return JsonResponse(result)




class CheckieView(View):
    """
    用try抛出异常
    """
#表单内查询
    def get(self,request,Page,PageSize):
        #print(Page,PageSize)
        #“直接获取GET请求中'queryString'参数的值”

        queryString=request.GET.get("queryString")
        print(queryString)

        if(queryString==None):
            print("获取检查项列表")
            Check_Item_list = TCheckitem.objects.filter( is_del=1)
            # 实例化Paginator分页器，将检查项列表Check_Item_list按照PageSize指定的大小进行分页
            paginator = Paginator(Check_Item_list, PageSize)
            # 获取指定页码的数据
            page_skus = paginator.page(Page)
            # 获取分页数据
            #total_page = paginator.num_pages
            #获取总条数
            total_count = paginator.count
            # 将分页器中的对象列表赋值给checkItem_list变量
            #checkItem_list = paginator.object_list
            # 获取指定页码的数据化为JSON格式的字符串，然后将其反序列化为Python对象（列表）
            Check_Item_Json_List = json.loads(serializers.serialize('json',page_skus))
            #print(Check_Item_Json_List)
            data_list = []
            for Check_Item_Json in Check_Item_Json_List:
                #if Check_Item_Json["fields"]["is_del"]==1:

                data_josn = Check_Item_Json["fields"]
                CheckItem_id = Check_Item_Json['pk']#取检查项id
                data_josn["id"]=CheckItem_id#将检查项id赋值给id字段
                #print(CheckItem_id)
                data_list.append(data_josn)
            result = {
                "status": "200",
                "message": "获取检查项成功",
                "total_count":total_count,
                "data": data_list

            }
            return JsonResponse(result)
        else:
            print("获取检查项列表")
            # 使用ORM方式，通过名称或代码中包含查询字符串来过滤检查项
            Check_Item_list = TCheckitem.objects.filter( Q(is_del=1) & Q(name__contains=queryString)| Q (code__contains=queryString) )
            # 实例化Paginator分页器，将检查项列表Check_Item_list按照PageSize指定的大小进行分页
            paginator = Paginator(Check_Item_list, PageSize)
            # 获取指定页码的数据
            page_skus = paginator.page(Page)
            # 获取分页数据
            # total_page = paginator.num_pages
            # 获取总条数
            total_count = paginator.count
            # 将分页器中的对象列表赋值给checkItem_list变量
            # checkItem_list = paginator.object_list
            # 获取指定页码的数据化为JSON格式的字符串，然后将其反序列化为Python对象（列表）
            Check_Item_Json_List = json.loads(serializers.serialize('json', page_skus))
            #print(Check_Item_Json_List)
            data_list = []
            for Check_Item_Json in Check_Item_Json_List:
                #if Check_Item_Json["fields"]["is_del"] == 1:
                data_josn = Check_Item_Json["fields"]
                CheckItem_id = Check_Item_Json["pk"]
                data_josn["id"] = CheckItem_id  # 将检查项id赋值给id字段
                #print(CheckItem_id)
                data_list.append(data_josn)
            result = {
                "status": "200",
                "message": "获取检查项成功",
                "total_count": total_count,
                "data": data_list

            }
            return JsonResponse(result)





    def post(self,request,Page,PageSize):
        request_json=request.body.decode("utf-8")
        print(request_json)
        data_dict=json.loads(request_json)
        TCheckitem.objects.create(
            code=data_dict["code"],
            name=data_dict["name"],
            sex=data_dict["sex"],
            age=data_dict["age"],
            price=data_dict["price"],
            type=data_dict["type"],
            remark=data_dict["remark"],
            attention=data_dict["attention"],
            is_del=1,
        )
        result = {
            "status": "200",

        }
        return JsonResponse(result)

    def put(self,request):
        request_json = request.body.decode("utf-8")

        data_dict = json.loads(request_json)
        Item=TCheckitem.objects.get(checkitem_id=data_dict["id"])
        Item.code=data_dict["code"]
        Item.name=data_dict["name"]
        Item.sex=data_dict["sex"]
        Item.age=data_dict["age"]
        Item.price=data_dict["price"]
        Item.type=data_dict["type"]
        Item.remark=data_dict["remark"]
        Item.attention=data_dict["attention"]
        Item.save()

        result = {
            "status": "200",

        }
        return JsonResponse(result)


    def delete(self,request):
        id=request.GET.get("id")

        print(id)
        checkitem = TCheckitem.objects.get(checkitem_id=id)
        checkitem.is_del=0
        checkitem.save()
        result = {
            "status": "200",
        }
        return JsonResponse(result)


